﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using System.Data.Entity; // needed for lambda includes

namespace TheCup.ApiControllers
{
    public class BlogController : ApiController
    {
        TheCupContext ctx = new TheCupContext();
        
        // GET api/<controller>
        public IEnumerable<Blog> Get()
        {
            return (from i in ctx.Blogs
                    select i)
                 .Include(p => p.Author)
                 .OrderByDescending(c => c.DateEntry).AsEnumerable();
        }

        public Blog Get(int id)
        {
            return (from i in ctx.Blogs
                     where i.Id == id
                     select i).Include(p => p.Author).First();
        }

        // GET api/<controller>/5
        public IHttpActionResult Details(int id)
        {
            Blog e = new Blog();

            e = ctx.Blogs.Include(p => p.Author).FirstOrDefault(b => b.Id == id);
            if (e == null)
            {
                return NotFound();
            }

            return Ok(e);
        }

        //[HttpPut]
        //[Route("Contact/{contactId:int}/name", Name = "UpdateContactName")]
        //[ResponseType(typeof(void))] // <- what should I put here? do I even need it at all?
        //public IHttpActionResult DummyForReference(int contactId, [FromBody] string name)
        //{
        //    return StatusCode(HttpStatusCode.Accepted);
        //}

        // POST api/<controller>
        [Authorize]
        public void Post([FromBody]Blog b)
        {
            ApiControllers.PlayerController pc = new PlayerController();
            Player author = pc.GetLoggedInPlayer();
            
            // do not remove!
            b.OldId = Guid.NewGuid();
            b.AuthorId = author.Id;
            b.DateEntry = DateTime.Now;
            
            ctx.Blogs.Add(b);
            ctx.SaveChanges();
        }

        // PUT api/<controller>/5
        [Authorize]
        public void Put(int id, [FromBody]Blog b)
        {
            Blog blog = ctx.Blogs.Where(x => x.Id == id).First();
            blog.Title = b.Title;
            blog.Content = b.Content;
            ctx.SaveChanges();
        }

        // DELETE api/<controller>/5
        [Authorize]
        public void Delete(int id)
        {
        }

    }

}